package com.dddframework.data.typehandlers;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 类型转换：Varchar <-> String[]，使用英文逗号,分割
 *
 * @author Jensen
 * @公众号 架构师修行录
 * @date 2021/9/12 14:52
 * @since jdk1.8
 */
@Slf4j(topic = "### BASE-DATA : TypeHandlers ###")
public class StringsTypeHandler extends BaseTypeHandler<String[]> {
    public StringsTypeHandler() {
        log.debug("Loading StringsTypeHandler, type: String[]");
    }

    public void setNonNullParameter(PreparedStatement ps, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        ps.setString(i, String.join(",", strings));
    }

    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String strings = rs.getString(columnName);
        return StrUtil.isBlank(strings) ? null : strings.split(",");
    }

    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String strings = rs.getString(columnIndex);
        return StrUtil.isBlank(strings) ? null : strings.split(",");
    }

    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String strings = cs.getString(columnIndex);
        return StrUtil.isBlank(strings) ? null : strings.split(",");
    }

}
